package com.why.controller;

import com.alibaba.fastjson.JSON;
import com.why.pojo.OrderDetail;
import com.why.pojo.Product;
import com.why.pojo.User;
import com.why.service.OrderDetailService;
import com.why.service.OrderService;
import com.why.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class OrderDetailsController {

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    ProductService productService;

    @Autowired
    OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    //订单详情
    @RequestMapping(value = "orderdetails",produces = "application/json;charset=utf-8")
    public String orderDetails(Integer orderId,HttpServletRequest request){
        List<OrderDetail> orderDetails = orderDetailService.selectByOrderId(orderId);
        List<Product> products = new ArrayList<>();
        for (int i=0;i<orderDetails.size();i++){
            Product product = productService.selectByPrimaryKey(orderDetails.get(i).getProductid());
            products.add(product);
        }
        List list = new ArrayList();
        list.add(orderDetails);
        list.add(products);
        list.add(orderService.selectByPrimaryKey(orderId));
        list.add(userData(request));
        return JSON.toJSONString(list);
    }

    //获取用户信息，由于本类调用
    public User userData(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //redis
        User user = null;
        for(Cookie cookie : cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> map = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                user = (User) map.get("user");
            }
        }
        return user;
    }
}
